package com.it.config;



import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@ComponentScan("com.it")
//@PropertySource("jdbc.properties")
@EnableTransactionManagement // 开启事务注解支持
public class TxConfig {
    /*
     * 【说明】：配置德鲁伊连接池
     * */
    @Value("com.mysql.cj.jdbc.Driver")
    private String driver;

    @Value("jdbc:mysql://localhost:3306/demo6?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true")
    private String url;

    @Value("root")
    private String username;

    @Value("123456")
    private String passwrod;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(passwrod);
        return dataSource;
    }

    // 配置 JdbcTemplate
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    // 配置事务
    @Bean
    public DataSourceTransactionManager manager(DataSource dataSource) {
        // 内部进行事务的操作、是基于连接池
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        // 需要连接池对象
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}
